//修改密码按钮
import React, { useState, useEffect } from "react";
import {Button, Checkbox, Form, Input, Modal, message,Select,Option} from 'antd'
import { Link, useRouter } from 'next/router';
import axios from 'axios';
const UpdatePassword = () => {
    const router = useRouter();
    //展开对话框
    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
     };

    const handleOk = async () => {
        setIsModalOpen(false);
        form.submit();
    };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //对话框中的表单
  const [form] = Form.useForm();
 
  const formItemLayout = {
    labelCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 8,
      },
    },
    wrapperCol: {
      xs: {
        span: 24,
      },
      sm: {
        span: 16,
      },
    },
  };
  
  const onFinish = (values) => {
    console.log('Request Body:', values); // 打印请求体内容
    const token = localStorage.getItem('token'); // 获取存储的token
  if (!token) {
    message.error('请先登录');
    router.push('/login');
    return;
  }
    axios.post('/api/user/update_password', values, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
      .then((response) => {
        console.log('Success:', response.data);
        message.success('修改成功');
      })
      .catch((error) => {
        console.log('Error:', error);
        // 登录失败时的处理
        if (error.response) {
          // 服务器返回了错误响应
          const errorMessage = error.response.data.msg || '修改失败';
          message.error(errorMessage);
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          message.error('请求失败，请检查网络连接');
        } else {
          // 发送请求时出了问题
          message.error('请求失败，请检查后端服务是否可用');
        }
      });
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };


return (
    <>
      <Button type="link" onClick={showModal}>修改密码</Button>
        <Modal title="修改密码" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form
      {...formItemLayout}
      form={form}
      name="register"
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      style={{
        maxWidth: 600,
      }}
      scrollToFirstError
    >
        <Form.Item
        name="old_password"
        label="Original Password"
        rules={[
          {
            required: true,
            message: 'Please input your original password!',
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        name="new_password"
        label="NewPassword"
        rules={[
          {
            required: true,
            message: 'Please input your password!',
          },
        ]}
        hasFeedback
      >
        <Input.Password />
      </Form.Item>

      <Form.Item
        name="repassword"
        label="Confirm Password"
        dependencies={['new_password']}
        hasFeedback
        rules={[
          {
            required: true,
            message: 'Please confirm your password!',
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('new_password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('The new password that you entered do not match!'));
            },
          }),
        ]}
      >
        <Input.Password />
      </Form.Item>
      </Form>
      </Modal>
    </>
);
    };
  export default UpdatePassword;